package cn.fayang.ymcc.service.impl;

import cn.fayang.ymcc.constant.util.AssertUtil;
import cn.fayang.ymcc.domain.AlipayInfo;
import cn.fayang.ymcc.domain.PayOrder;
import cn.fayang.ymcc.dto.AlipayNotifyDto;
import cn.fayang.ymcc.dto.PayApplyDto;
import cn.fayang.ymcc.dto.PayNotifyDto;
import cn.fayang.ymcc.exception.GlobalException;
import cn.fayang.ymcc.mapper.PayOrderMapper;
import cn.fayang.ymcc.service.IAlipayInfoService;
import cn.fayang.ymcc.service.IPayOrderService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.kernel.Config;
import com.alipay.easysdk.kernel.util.ResponseChecker;
import com.alipay.easysdk.payment.common.models.AlipayTradeCloseResponse;
import com.alipay.easysdk.payment.page.Client;
import com.alipay.easysdk.payment.page.models.AlipayTradePagePayResponse;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.LocalTransactionState;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.client.producer.TransactionSendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.Map;

/**
 * 处理支付相关
 */
@Service
@Slf4j
public class PayOrderServiceImpl extends ServiceImpl<PayOrderMapper, PayOrder> implements IPayOrderService {
    @Autowired
    private IAlipayInfoService alipayInfoService;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Override
    public PayOrder selecByOrderNO(String orderNo) {
        Wrapper<PayOrder> wrapper = new EntityWrapper<>();
        wrapper.eq("order_no",orderNo);
        return selectOne(wrapper);
    }

    /**
     * 发起支付
     * @param dto
     * @return
     */
    @Override
    public String apply(PayApplyDto dto) {
        // 非空校验
        PayOrder payOrder = selecByOrderNO(dto.getOrderNo());
        AssertUtil.isNotNull(payOrder,"支付单不存在！！！");
        // 订单状态校验
        boolean wait = payOrder.getPayStatus() == PayOrder.STATE_WAIT_PAY;
        AssertUtil.isTrue(wait,"支付单状态异常，发起支付失败！！！");
        // 判断支付方式
        if(payOrder.getPayType() == 1){
           return alipay(payOrder,dto);
        } else if (payOrder.getPayType() == 2) {

        }
        return null;
    }

    /**
     * 调用支付宝支付，返回Form表单
     * @return
     * @throws Exception
     */
    public String alipay(PayOrder payOrder,PayApplyDto dto){
        AlipayInfo info = alipayInfoService.selectOne(null);
        // 1. 设置参数（全局只需设置一次）
        Factory.setOptions(getOptions(info));
        try {
            // 2. 网页端支付
            Client page = Factory.Payment.Page();
            //封装支付相关参数，发起支付
            AlipayTradePagePayResponse response = page.pay(
                    payOrder.getSubject(),
                    payOrder.getOrderNo(),
                    payOrder.getAmount().toString(),
                    StringUtils.isEmpty(dto.getCallUrl())?info.getReturnUrl():dto.getCallUrl()//同步回调地址
            );
            // 3. 处理响应或异常
            if (ResponseChecker.success(response)) {
                System.out.println("调用成功");
                return response.getBody();//Form表单
            } else {
                System.err.println("调用失败，原因：");
                throw new GlobalException("支付调用失败！！！");
            }
        } catch (Exception e) {
            System.err.println("调用遭遇异常，原因：" + e.getMessage());
            throw new RuntimeException(e.getMessage(), e);
        }
    }

    public Config getOptions(AlipayInfo info) {
        Config config = new Config();
        config.protocol = info.getProtocol();
        config.gatewayHost = info.getGatewayHost();//沙箱API地址
        config.signType = info.getSignType();
        config.appId = info.getAppId();
        // 为避免私钥随源码泄露，推荐从文件中读取私钥字符串而不是写入源码中
        config.merchantPrivateKey = info.getMerchantPrivateKey();
        //注：如果采用非证书模式，则无需赋值上面的三个证书路径，改为赋值如下的支付宝公钥字符串即可
        config.alipayPublicKey = info.getAlipayPublicKey();
        //可设置异步通知接收服务地址（可选）
        config.notifyUrl = info.getNotifyUrl();
        //可设置AES密钥，调用AES加解密相关接口时需要（可选）
        config.encryptKey = "";
        return config;
    }

    /**
     * 处理支付成功之后的异步回调逻辑
     * @param dto
     * @return
     */
    @Override
    public String notify(AlipayNotifyDto dto) throws Exception{
        // 支付宝需要map结构的数据,将数据转换为map结构
        String jsonString = JSON.toJSONString(dto);
        Map<String,String> dtoMap = JSONObject.parseObject(jsonString, Map.class);
        Boolean isValid = Factory.Payment.Common().verifyNotify(dtoMap);
        // 校验回调参数是否正确
        if(!isValid){
            return "Fail";
        }
        PayOrder payOrder = selecByOrderNO(dto.getOut_trade_no());
        if(payOrder== null){
            return "Fail";
        }
        if(payOrder.getPayStatus() != PayOrder.STATE_WAIT_PAY){
            return "Fail";
        }

        String trade_status = dto.getTrade_status();
        if(!trade_status.equals(AlipayNotifyDto.TRADE_SUCCESS)){
            return "Fail";
        }
        // 修改支付单参数----支付状态&修改时间
        payOrder.setPayStatus(PayOrder.STATE_PAY_SUCCESS);
        payOrder.setUpdateTime(new Date());
        // 额外参数
        PayNotifyDto payNotifyDto = new PayNotifyDto(
                payOrder.getOrderNo(),
                payOrder.getExtParams()
        );

        log.info("发送支付成功通知事务消息");
        // 设置消息体
       Message<String> message = MessageBuilder.withPayload(JSON.toJSONString(payNotifyDto)).build();
       // 发布事务消息
        TransactionSendResult transactionSendResult = rocketMQTemplate.sendMessageInTransaction(
                "service-pay-tx-group",//要和监听器上注解申明的名字一致
                "pay-notify-topic:pay-notify-tag",
                message,  //消息体
                payOrder   //额外参数
        );
        // 异步消息返回结果
        LocalTransactionState localTransactionState = transactionSendResult.getLocalTransactionState();
        SendStatus sendStatus = transactionSendResult.getSendStatus();
        if(localTransactionState != LocalTransactionState.COMMIT_MESSAGE || sendStatus != SendStatus.SEND_OK ){
            throw new GlobalException("处理支付成功结果失败！！");
        }

        return "success";
    }

    @Override
    public void cancelOrder(String orderNo) {
        PayOrder payOrder = selectByOrderNo(orderNo);
        //取消支付单
        if(payOrder.getPayStatus().intValue() == PayOrder.STATE_WAIT_PAY){
            payOrder.setPayStatus(PayOrder.STATE_CANCEL);
            updateById(payOrder);
        }
        //调用支付宝，关闭支付
        try {
            AlipayTradeCloseResponse close = Factory.Payment.Common().close(orderNo);
        } catch (Exception e) {
            e.printStackTrace();
            /**
             * 做兜底
             * 1.重试3次
             * 2.保存要取消支付单的记录到数据库，运维人员来人工跟进
             * 3.给运维人员发站内信，邮件，消息---- 对接钉钉推销
             */
        }
    }

    private PayOrder selectByOrderNo(String orderNo) {
        Wrapper<PayOrder> wrapper = new EntityWrapper<>();
        wrapper.eq("order_no",orderNo);
        return selectOne(wrapper);
    }

}
